<?php
/**
 * Authenticate
 *
 * Is the user who she says she is? If so, set $self::RESULT.
 *
 * The _preDispatch method is general enough to handle the
 * results of the auth() method appropriately. The auth() section
 * needs to call $this->result() passing the appropriate static
 * code.
 */

class Authenticate extends Spaph_Plugin
{
    public static $PASSTHRU = 1;                   // Do not authenticate user
    public static $SUCCESS  = 2;                   // Credentials are true
    public static $FAILURE  = 3;                   // This the default value of $RESULT
    public static $FAILURE_IDENTITY_NOT_FOUND = 4; // Could not find user
    public static $FAILURE_CREDENTIAL_INVALID = 5; // The credentials (password) are bad
    public static $FAILURE_IDENTITY_AMBIGUOUS = 6; // A piece of the puzzle was missing or invalid
    public static $FAILURE_USER_EXPIRED       = 7; // The user has expired

    // This will equal one of the static codes above
    private static $RESULT;

    public function _preDispatch()
    {
        // Always say no :-)
        $this->result(self::$FAILURE);

        // Authenticate, customize auth()
        $this->auth();

        // Handle result() set during auth()
        switch($this->result()) {
            case self::$PASSTHRU:
            case self::$SUCCESS:
                break;

            case self::$FAILURE:
            case self::$FAILURE_IDENTITY_NOT_FOUND:
            case self::$FAILURE_CREDENTIAL_INVALID:
            case self::$FAILURE_IDENTITY_AMBIGUOUS:
            case self::$FAILURE_USER_EXPIRED:
                break;

            default:
                throw new Exception('Authentication result is invalid');
        }
    }

    /**
     * Return authentication results
     *
     * @input  integer $code
     * @return integer self::$RESULT
     */
    public function result($code = null) {
        if(isset($code))
            self::$RESULT = $code;

        return self::$RESULT;
    }

    /**
     * authenticate the user. Set self::$RESULT appropriately by using
     * the result() method.
     */
    private function auth()
    {
        // Grab a spaph instance
        $spaph = Spaph::getInstance();

        // Just passthru if this is not an auth request.
        if(! (isset($_POST['username']) && isset($_POST['password'])) ) {
            $this->result(self::$PASSTHRU);
            return;
        }

        // Do some sort of authentication...
        // If successfull, then $this->result(self::$SUCCESS);
        // Maybe start a session with $spaph->session_start(session_name(), 1);

        // If authentication fails, then $this->result(self::$FAILURE_CREDENTIAL_INVALID);
        // Redirect or change action $spaph->setAction('user.signin');

        return;
    }
}
